package model.tokens;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

import model.parser.Parser;
import model.parser.ParserException;
import model.semantics.LeftGroupNode;
import model.semantics.Node;

/**
 * Left parenthesis.
 */

public class LeftBlockToken<T> extends Token<T> {

    public LeftBlockToken(TokenConstructorArguments<T> args) {
        super(args);
    }

    /**
     * Get all the tokens inside a bracketed expression, and return them,
     * omitting the brackets.
     */
    private Queue<Token<T>> getBracketedTokens(Queue<Token<T>> tokens) {
        Queue<Token<T>> out = new LinkedList<Token<T>>();

        int leftGroups = 1;

        while (true) {
            if (tokens.isEmpty()) {
                throw ParserException.BAD_SYNTAX;
            }

            Token<T> token = tokens.poll();
            if (token instanceof LeftBlockToken)
                leftGroups++;
            else if (token instanceof RightBlockToken) {
                leftGroups--;
                // Don't add the last right bracket to the output.
                if (leftGroups == 0)
                    break;
            }
            out.add(token);
        }

        return out;
    }

    @Override
    public void process(Automaton<T> state) {
        Token.shuntFunctionsToOutput(state.operatorStack, state.output);
        Queue<Token<T>> innerTokens = getBracketedTokens(state.tokens);
        state.output.add(new Parser<T>(state.getTokenFile(), state
                .getSyntaxFile()).parse(innerTokens));
        Token.shuntFunctionsToOutput(state.operatorStack, state.output); // FIXME
    }

}
